package com.jushu.storbox.fragment;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.actions.Actions;
import com.jushu.storbox.actions.MoveAction;
import com.jushu.storbox.adapter.MoveAdapter;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.entities.FileType;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.ClouddriveDialog;
import com.jushu.storbox.view.pulltorefresh.MyScrollView;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.request.FolderListRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderListResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;

public class AllMoveFragment extends BaseFragment {

	/** ShareFragment TAG */
	public static final String TAG = "AllMoveFragment";
	/** activity */
	private Activity activity;
	/** activity handler */
	private Handler activityHandler;
	/** cloudriverService */
	private ICloudDriveService shareDriveService;
	/** move parent */
	private FileFolderInfo parentInfo;
	/** contentView */
	private View contentView;
	/** ListView */
	private ListView FileList_lv;
	/** canccle_btn */
	private List<FileFolderInfo> list;
	private int index = 0;
	private MyScrollView moveScr;
	private LinearLayout moveLL;
	private Actions actions;
	private String returnParent;
	private LinearLayout loading_ll;

	/**
	 * onAttach
	 * 
	 * @param activity
	 *            Activity instance
	 */
	@Override
	public void onAttach(Activity activity) {
		LogUtil.i(TAG, "onAttach Activity");
		this.activity = activity;
		setBack(false);
		if (null == getObj()) {
			System.exit(1);
		} else {
			Map<String, Object> mp = (Map<String, Object>) getObj();
			if (null != mp.get("activityhandler")) {
				activityHandler = (Handler) mp.get("activityhandler");
			} else {
				// PublicTools.restartApp(activity);
			}
			if (null != mp.get("service")) {
				shareDriveService = (ICloudDriveService) mp.get("service");
			} else {
				PublicTools.restartApp(activity);
			}
			parentInfo = (FileFolderInfo) mp.get("move_entity");
			if (null != parentInfo) {
				returnParent = parentInfo.getName();
			}
			if (null != mp.get("index")) {
				index = (Integer) mp.get("index");
			}
			actions = new Actions(activity);
		}
		super.onAttach(activity);
		
	}
	
	private ClientExceptionRelateHandler checkHandler = new ClientExceptionRelateHandler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MessageCode.GET_FILE_LIST:
				Map<String,Object> objResult = (Map<String,Object>)msg.obj;
				FileFolderInfo srcItemObj = (FileFolderInfo)objResult.get("srcObj");
				FolderListResponseV2 response = (FolderListResponseV2)objResult.get("targetObj");
				boolean existSameName = false;
				if(FileType.File.value() == srcItemObj.getIsFile()){
					List<FileInfoResponseV2> fileList = response.getFiles();
					for(FileInfoResponseV2 file : fileList){
						if(srcItemObj.getName().equalsIgnoreCase(file.getName())){
							existSameName = true;
							break;
						}
					}
				}else{
					List<FolderResponse> folderList = response.getFolders();
					for(FolderResponse folder : folderList){
						if(srcItemObj.getName().equalsIgnoreCase(folder.getName())){
							existSameName = true;
							break;
						}
					}
				}
				if(existSameName){
					final ClouddriveDialog renameTipDialog = new ClouddriveDialog(activity, R.style.dialog_upload,
	                        R.layout.dialog_common);
	                    View conventView = renameTipDialog.getConventView();
	                    Button dialog_cancal = (Button) conventView.findViewById(R.id.dialog_add_file_cancal_bt);
	                    Button dialog_OK = (Button) conventView.findViewById(R.id.dialog_add_file_ok_bt);
	                    TextView dialog_prompt_tv = (TextView) conventView.findViewById(R.id.dialog_prompt_tv);
	                    dialog_prompt_tv.setText(activity.getString(R.string.exist_same_name_obj));
	                    
	                    dialog_cancal.setOnClickListener(new View.OnClickListener()
	                    {
	                        @Override
	                        public void onClick(View v)
	                        {
	                            renameTipDialog.dismiss();
	                            moveCancle();
	                        }
	                    });
	                    
	                    dialog_OK.setOnClickListener(new View.OnClickListener()
	                    {
	                        @Override
	                        public void onClick(View v)
	                        {
	                            renameTipDialog.dismiss();
	                            Log.d("moverespnse", "MOVESUCCESSCODE[moveConfirm]");
	        					Intent intent = new Intent();
	        					Bundle bundle = new Bundle();
	        					bundle.putSerializable("parentInfo", parentInfo);
	        					intent.putExtra("moverespnse", bundle);
	        					activity.setResult(4, intent); 
	        					activity.finish();
	                        }
	                    });
	                    renameTipDialog.show();
				}else{
					Log.d("moverespnse", "MOVESUCCESSCODE[moveConfirm]");
					Intent intent = new Intent();
					Bundle bundle = new Bundle();
					bundle.putSerializable("parentInfo", parentInfo);
					intent.putExtra("moverespnse", bundle);
					activity.setResult(4, intent); 
					activity.finish();
				}
				break;
			default:
				super.handleMessage(msg);
				break;
			}
		}

		@Override
		public Context getContext() {
			return activity;
		}
		
	};

	/**
	 * onCreate in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		LogUtil.i(TAG, "onCreate()");
		super.onCreate(savedInstanceState);
	}

	/**
	 * onCreateView in Fragment
	 * 
	 * @param inflater
	 *            LayoutInflater
	 * @param container
	 *            ViewGroup
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		LogUtil.i(TAG, "onCreateView method");
		contentView = LayoutInflater.from(getActivity()).inflate(
				R.layout.window_move, null);
		initFindViewById();
		initData();
		initListenser();
		return contentView;
	}
	
	public void moveConfirm(final Object srcObj) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				FolderListRequestV2 request = new FolderListRequestV2();
				request.setFolderID(parentInfo == null ? "0" : parentInfo.getId());
				request.setLimit(1000);
				request.setOffset(0);
				request.setOwnerID(ShareDriveApplication.getInstance().getWnerID());
				FolderListResponseV2 response = new MoveAction(activity).getFileList(shareDriveService, request, checkHandler);
				if(response != null){
					Message message = new Message();
					Map<String,Object> objResult = new HashMap<String,Object>();
					objResult.put("srcObj", srcObj);
					objResult.put("targetObj", response);
					message.what = MessageCode.GET_FILE_LIST;
					message.obj = objResult;
					checkHandler.sendMessage(message);
				}
			}
		}).start();
	}

	public void moveCancle() {
		Log.d("moverespnse", "MOVESUCCESSCODE[moveCancle]");
		// activityHandler.sendEmptyMessage(8);
		Intent intent = new Intent();
		activity.setResult(5, intent); 
		activity.finish();
	}

	private void initListenser() {
	}

	private void initData() {
		moveScr.setLayout(moveLL);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// TODO Auto-generated method stub
					String folderId = "0";
					if (null != parentInfo) {
						folderId = parentInfo.getId();
					}
					list = getMoveFolderList(ShareDriveApplication.getInstance().getWnerID(),folderId, null);
					Message msg = new Message();
					msg.what = 0;
					msg.obj = list;
					handler.sendMessageDelayed(msg, 500);
				} catch (ClientException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void initFindViewById() {
		FileList_lv = (ListView) contentView.findViewById(R.id.FileList_lv);
		moveScr = (MyScrollView) contentView.findViewById(R.id.move_scrollview);
		moveLL = (LinearLayout) contentView.findViewById(R.id.move_layout);
		loading_ll = (LinearLayout) contentView.findViewById(R.id.loading_ll);
		if (View.GONE == loading_ll.getVisibility()) {
			loading_ll.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * onActivityCreated in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		LogUtil.i(TAG, "onActivityCreated()");
		super.onActivityCreated(savedInstanceState);
	}

	/**
	 * onStart in Fragment
	 */
	@Override
	public void onStart() {
		LogUtil.i(TAG, "onStart()");
		super.onStart();
	}

	/**
	 * onResume in Fragment
	 */
	@Override
	public void onResume() {
		LogUtil.i(TAG, "onResume()");
		super.onResume();
	}

	/**
	 * onPause in Fragment
	 */
	@Override
	public void onPause() {
		LogUtil.i(TAG, "onResume()");
		super.onPause();
	}

	/**
	 * onSaveInstanceState in Fragment
	 * 
	 * @param savedInstanceState
	 *            Bundle
	 */
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		LogUtil.i(TAG, "onSaveInstanceState()");
		super.onSaveInstanceState(savedInstanceState);
	}

	/**
	 * onStop in Fragment
	 */
	@Override
	public void onStop() {
		LogUtil.i(TAG, "onStop()");
		super.onStop();
	}

	/**
	 * onDestroy in Fragment
	 */
	@Override
	public void onDestroy() {
		LogUtil.i(TAG, "onDestroy()");
		super.onDestroy();
	}

	/**
	 * onDestroyView in Fragment
	 */
	@Override
	public void onDestroyView() {
		LogUtil.i(TAG, "onDestroyView()");
		super.onDestroyView();
	}

	/**
	 * onDetach in Fragment
	 */
	@Override
	public void onDetach() {
		LogUtil.i(TAG, "onDetach()");
		super.onDetach();
	}

	private void showMsgData() {
		setBack(true);
		if (View.VISIBLE == loading_ll.getVisibility()) {
			loading_ll.setVisibility(View.GONE);
		}
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				moveScr.removeAllItem();
				List<FileFolderInfo> list = (List<FileFolderInfo>) msg.obj;
				MoveAdapter adapter = new MoveAdapter(activity, handler, list);
				moveScr.setAdptor(adapter);
				moveScr.notifyAllItem();
				showMsgData();
				break;
			case 1:
				list = null;
				Message moveMsg = new Message();
				moveMsg.obj = msg.obj;
				moveMsg.what = 2;
				moveMsg.arg1 = 0;
				activityHandler.sendMessage(moveMsg);
				break;
			default:
				break;
			}
		};
	};

	private List<FileFolderInfo> getMoveFolderList(String ownerId, String folderId,
			String exception) throws ClientException {
		List<FileFolderInfo> moveList = null;
		if (null != shareDriveService) {
			moveList = shareDriveService.getMoveFolderListDB(ownerId, folderId,
					exception);
			// for (int i = 0; i < moveList.size(); i++) {
			// Log.d("dsdsd22", "name:" + moveList.get(i).getName());
			// }
		}
		return moveList;

	}

	@Override
	public void refreshListFromServer() {
		// TODO Auto-generated method stub
	}

	@Override
	public String getParent() {
		// TODO Auto-generated method stub
		return returnParent;
	}

	@Override
	public void onDataLoaded() {
		// TODO Auto-generated method stub
	}

	@Override
	public View getConventview() {
		// TODO Auto-generated method stub
		return contentView;
	}
}
